package servlet;

import qin.com.Users;
import qin.com.UsersDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ServletUsers",urlPatterns = {"/users"})
public class ServletUsers extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");
        String pass=request.getParameter("pass");
        String action=request.getParameter("action");
        Users users=null;
        System.out.println(action);
        if("insert".equals(action)){
            users=new Users();
            users.setName(name);
            users.setPass(pass);
            if(UsersDao.insert(users)){
                response.sendRedirect("listusers.jsp");
            }else {
                response.getWriter().println("add error <a href=listusers.jsp>forward to listusers</a>");
            }
        }
        if("updata".equals(action)){
            users=new Users();
            users.setName(name);
            users.setPass(pass);
            long id=Long.parseLong(request.getParameter("id"));
            users.setId(id);
            if(UsersDao.update(users)){
                response.sendRedirect("listusers.jsp");
            }else {
                response.getWriter().println("update error <a href=listusers.jsp>forward to listusers</a>");
            }
        }
        if("del".equals(action)){
            long id=Long.parseLong(request.getParameter("id"));
            if(UsersDao.del(id)){
                response.sendRedirect("listusers.jsp");
            }else {
                response.getWriter().println("del error <a href=listusers.jsp>forward to listusers</a>");
            }
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
